
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:package_info/package_info.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import 'package:schoolassets/%E9%A6%96%E9%A1%B5/Home.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/RSATools.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/Setting.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/ShowToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/requestUrl.dart';
import 'package:shared_preferences/shared_preferences.dart';
/**
 * Creat For 11643
 * CreatTime 2022/8/11
 * Description:登录
 *
 */
class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  ///  点击返回的次数
  int BackNum = 0;
  int last = 0;
  /// 响应空白处的焦点的Node
  FocusNode blankNode = FocusNode();
//控制密码显示隐藏
  bool passwordVisible = false;
//是否记住密码
  bool check = false;
//手机号
  var _Phone = "";
  /**
   * 密码
   */

  var _Password = "";
  ///公钥
  String PublicKey = "";
//上下文
  late BuildContext Logincontext;

  PackageInfo _packageInfo = PackageInfo(
    appName: 'Unknown',
    packageName: 'Unknown',
    version: 'Unknown',
    buildNumber: 'Unknown',
  );
  //本地缓存初始化
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  //输入框控制器
  TextEditingController _PasswordController = TextEditingController();
  TextEditingController _PhoneController = TextEditingController();


  @override
  void initState() {
    super.initState();
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,        //状态栏背景颜色
        statusBarIconBrightness: Brightness.dark  // dark:一般显示黑色   light：一般显示白色
    ));
    Future.delayed(Duration.zero,() async {
      final PackageInfo info = await PackageInfo.fromPlatform();
      _packageInfo = info;
      SharedPreferencesIsCheck();
      //获取公钥
      // GetPublicKey();
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Builder(
          builder: (context) => Scaffold(

            backgroundColor: Colors.white,
            body: SingleChildScrollView(
              child: WillPopScope(
                child: Column(
                  children: [
                    Stack(
                      alignment: Alignment.topCenter,
                      children: [
                        Container(
                          height: 250,
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage("Image/LoginBack.png"),
                              fit: BoxFit.fill,
                            ),
                          ),
                        ),
                        Column(
                          children: [
                            Container(
                              margin: EdgeInsets.only(top: 50),
                              height: 80,
                              width: 80,
                              child: Card(
                                // shape: RoundedRectangleBorder(
                                //     borderRadius:
                                //     BorderRadiusDirectional.circular(
                                //         20)),
                                clipBehavior: Clip.antiAlias,
                                child: Image.asset(
                                  "Image/LOGO.png",
                                  width: double.maxFinite,
                                ),
                              ),
                            ),
                            Container(
                              height: 5,
                            ),
                            Container(
                              child: Text(
                                "固定资产管理系统",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 20,
                                    fontWeight: FontWeight.w600),
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                    // 账号
                    Container(
                        margin:
                        EdgeInsets.only(left: 30, top: 50, right: 30),
                        child: Row(
                          children: [
                            Container(
                              child: Icon(
                                Icons.phone_android,
                                // color: Color(0xff1bccb9),
                                color: Color(0xff1bccb9),
                                size: 30,
                              ),
                            ),
                            Container(
                              width: 15,
                            ),
                            Expanded(
                              child: TextField(
                                cursorColor: Color(0xff1bccb9),
                                controller: _PhoneController,
                                decoration: InputDecoration(
                                  hintText: "请输入账号",
                                  hintStyle: TextStyle(
                                      fontSize: 13,
                                      color: Colors.black26),
                                  enabledBorder: UnderlineInputBorder(
                                      borderSide: BorderSide(
                                        width: 0.5,
                                        color: Colors.black26,
                                      )),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Color(0xff1bccb9),),
                                  ),
                                ),
                              ),
                            )
                          ],
                        )),
                    // 密码
                    Container(
                        margin:
                        EdgeInsets.only(left: 30, top: 30, right: 30),
                        child: Row(
                          children: [
                            Container(
                              child: Icon(
                                Icons.https,
                                color: Color(0xff1bccb9),
                                size: 30,
                              ),
                            ),
                            Container(
                              width: 15,
                            ),
                            Expanded(
                              child: TextField(
                                obscureText: passwordVisible,
                                controller: _PasswordController,
                                decoration: InputDecoration(
                                  hintText: "请输入密码",
                                  hintStyle: TextStyle(
                                      fontSize: 13,
                                      color: Colors.black26),
                                  suffixIcon: IconButton(
                                    icon: Icon(passwordVisible
                                        ? Icons.visibility_off
                                        : Icons.visibility,color: passwordVisible
                                        ?Colors.black26:Color(0xff1bccb9),),
                                    onPressed: () {
                                      setState(() {
                                        passwordVisible =
                                        !passwordVisible;
                                      });
                                    },
                                  ),
                                  enabledBorder: UnderlineInputBorder(
                                      borderSide: BorderSide(
                                          width: 0.5,
                                          color: Colors.black26)),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Color(0xff1bccb9),),
                                  ),
                                ),
                              ),
                            )
                          ],
                        )),
                    RememberPassword(context),
                    Container(
                      margin: EdgeInsets.fromLTRB(100, 50, 100, 0),
                      decoration: BoxDecoration(
                        // gradient: LinearGradient(colors: [
                        //   // Colors.white12,
                        //   Color(0xff1bbff4),
                        //   Color(0xff1bccb9)
                        // ]), // 渐变色
                          borderRadius: BorderRadius.circular(25)),
                      child: RaisedButton(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25)),
                        color: Color(0xff1bccb9), // 设为透明色
                        elevation: 0, // 正常时阴影隐藏
                        highlightElevation: 0, // 点击时阴影隐藏
                        onPressed: () {
                          GetPublicKey(context);
                          // if(_PhoneController.text=="admin"||_PhoneController.text=="Admin"){
                          //   Navigator.push(context, MaterialPageRoute(builder: (context)=>Home()));
                          // }else{
                          //   ShowToast().MyToast("账号或密码错误！");
                          //   return;
                          // }
                        },
                        child: Container(
                          alignment: Alignment.center,
                          child: Text(
                            '登 录',
                            style: TextStyle(
                                color: Colors.white, fontSize: 15),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      height: 15,
                    ),
                    Container(
                      child: Text("V${_packageInfo.version}",style: TextStyle(color: Colors.black),),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width/2,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [

                          Expanded(child: Container(
                            child: TextButton(child: Text("服务器地址设置",style: TextStyle(color: Colors.blue,fontSize: 15)),onPressed: (){
                              //  进入服务器地址设置页面
                              Navigator.push(context, MaterialPageRoute(builder: (context)=>Setting()));
                            },),
                          ))
                        ],
                      ),
                    )
                  ],
                ),
                onWillPop: () async {
                  //计算两次时间间隔
                  int now = DateTime.now().millisecondsSinceEpoch;
                  if (now - last > 8000) {
                    last = DateTime.now().millisecondsSinceEpoch;
                    ShowToast().MyToast('再次点击返回退出应用');
                    return Future.value(false);
                  } else {
                    return Future.value(true);
                  }
                },
              ),

            ),
          )),
    );
  }
  //忘记密码和记住密码
  Widget RememberPassword(context) {
    return Container(
      padding: EdgeInsets.only(left: 20, right: 20),
      margin: EdgeInsets.only(top: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              RoundCheckBox(
                  size: 15,
                  checkedWidget: const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 10,
                  ),
                  checkedColor: Color(0xff1bccb9),
                  uncheckedColor: Color(0x003C78FF),
                  border: Border.all(color: getCheckBoxBorderColor(), width: 1),
                  isChecked: check,
                  onTap: (selected) {
                    check = selected!;
                    setState(() {});
                  }),
              Container(
                margin: EdgeInsets.only(left: 5),
                child: Text(
                  "记住密码",
                  style: TextStyle(fontSize: 12, color: Colors.black38),
                ),
              )
            ],
          ),
          //忘记密码
          // GestureDetector(
          //   child: Container(
          //       child: Text("忘记密码?",
          //           style: TextStyle(color: Color(0xff1bccb9), fontSize: 12))),
          //   onTap: () {},
          // ),
        ],
      ),
    );
  }
  //复选框选中事件
  getCheckBoxBorderColor() {
    if (check) {
      return Color(0xff1bccb9);
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  //检测本地缓存是否记住密码/
  Future<void> SharedPreferencesIsCheck() async {
    //读取本地缓存，查看是否记住密码
    final SharedPreferences prefs = await _prefs;
    final bool? SharedIsCheck = prefs.getBool('Check');
    String SharedPhone = prefs.getString('Phone').toString();
    String SharedPassword = prefs.getString('Password').toString();
    if (SharedIsCheck == true) {
      check = true;
    } else {
      check = false;
      SharedPhone = "";
      SharedPassword = "";
    }
    _PasswordController = new TextEditingController(text: SharedPassword);
    _PhoneController = new TextEditingController(text: SharedPhone);
    setState(() {});
  }
  // 登录
  Future<void> StartLogin(context) async {
    var ResponseData;

    // 获取本地token
    final SharedPreferences sharedPreferences =
    await SharedPreferences.getInstance();

// 获取本地ip地址
    var ApiUrl = sharedPreferences.getString('ApiUrl');
    print("服务器地址:$ApiUrl");
    if (ApiUrl == null) {
      // 如果没有设置IP地址
      //默认地址为公网地址
      ApiUrl = "http://192.168.43.147:1090";
      //地址保存本地
      sharedPreferences.setString("ApiUrl",ApiUrl);
    }
    ///加密后的密码
    String RSAPassword =await RSATools().encodeString(_PasswordController.text, PublicKey);
    ResponseData = await new requestUrl().CommenRequest(
        '/api/Public/LogonValidate', 'post', {"user": _PhoneController.text,"pwd":RSAPassword,"type":"app","cid":"123","version":_packageInfo.version}, "登录中...", context, true,"application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      // 本地保存个人信息
      SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();
      //登陆成功后,本地保存是否记住密码
      await sharedPreferences.setBool('Check',check);
      await sharedPreferences.setString('Phone', _PhoneController.text);
      await sharedPreferences.setString('Password', _PasswordController.text);
      await sharedPreferences.setString("Token",Uri.encodeComponent(ResponseData['data']));
      ShowToast().MyToast("登陆成功!");
      Navigator.push(context, MaterialPageRoute(builder: (context)=>Home()));
    } else {
      ShowToast().MyToast(ResponseData['msg']);
    }
  }
//获取公钥
GetPublicKey(context) async {
  var ResponseData;
  ResponseData = await new requestUrl().CommenRequest(
      '/api/Public/AppGetRsaPublicKey', 'post', {
  }, "获取公钥中...", context, false, "");
  if (ResponseData['code'] == 0) {
    PublicKey = ResponseData['data'];
    print("公钥:$PublicKey");
    StartLogin(context);
    setState(() {});
  } else {
    ShowToast().MyToast('无法获取公钥');
  }
}
}
